package cn.lg.soar.system.api.handler;

import cn.lg.soar.common.util.current.ICurrentUser;
import cn.lg.soar.common.util.current.UserContext;
import cn.lg.soar.core.config.cache.template.ICacheTemplate;
import cn.lg.soar.core.util.SoarSubscriber;
import cn.lg.soar.system.api.service.ITokenCurrBindApi;
import cn.lg.soar.system.api.service.IUserCurrBindApi;

import java.util.Map;

/**
 * 当前绑定上下文
 * @author luguoxiang
 * @date 2022/3/29
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class BindContext extends UserContext {

    protected static final String TOKEN_KEY_PREFIX = "$:";
    protected static final String USER_KEY_PREFIX = "@:";

    private static ICacheTemplate<String, Object> cacheTemplate;
    private static ITokenCurrBindApi tokenCurrBindApi;
    private static IUserCurrBindApi userCurrBindApi;

    /**
     * 获取token绑定
     * @return
     */
    protected static Map<String, Object> getTokenBind() {
        // 读取远程缓存
        ICurrentUser user = getUser();
        Object o = cacheTemplate.get(TOKEN_KEY_PREFIX + user.getTokenId());
        if (o == null) {
            // 读取数据库
            o = tokenCurrBindApi.get();
            // 压入远程缓存
            cacheTemplate.put(TOKEN_KEY_PREFIX + user.getTokenId(), o, 1800000);
        }
        return (Map<String, Object>)o;
    }

    /**
     * 压入token绑定
     * @param map
     */
    protected static void putTokenBind(Map<String, Object> map) {
        ICurrentUser user = getUser();
        cacheTemplate.put(TOKEN_KEY_PREFIX + user.getTokenId(), map, 1800000);
    }

    /**
     * 删除token绑定
     */
    protected static void delTokenBind() {
        ICurrentUser user = getUser();
        cacheTemplate.delete(TOKEN_KEY_PREFIX + user.getTokenId());
    }


    /**
     * 获取用户绑定
     * @return
     */
    protected static Map<String, Object> getUserBind() {
        // 读取远程缓存
        ICurrentUser user = getUser();
        Object o = cacheTemplate.get(USER_KEY_PREFIX + user.getId());
        if (o == null) {
            // 读取数据库
            o = userCurrBindApi.get();
            // 压入远程缓存
            cacheTemplate.put(USER_KEY_PREFIX + user.getId(), o, 1800000);
        }
        return (Map<String, Object>)o;
    }

    /**
     * 压入用户绑定
     * @param map
     */
    protected static void putUserBind(Map<String, Object> map) {
        cacheTemplate.put(USER_KEY_PREFIX + getUserId(), map, 1800000);
    }

    /**
     * 删除用户绑定
     */
    protected static void delUserBind() {
        cacheTemplate.delete(USER_KEY_PREFIX + getUserId());
    }


    static {
        SoarSubscriber.subscribeRunner(applicationContext -> {
            tokenCurrBindApi = applicationContext.getBean(ITokenCurrBindApi.class);
            userCurrBindApi = applicationContext.getBean(IUserCurrBindApi.class);
            cacheTemplate = applicationContext.getBean(ICacheTemplate.class);
        });
    }
}
